package com.icrazy.platform.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

/**
 * Jackson JSON处理类
 * 
 * @author xiaofeng
 * 
 * @version 1.0 2011-4-27
 */
@SuppressWarnings({ "rawtypes", "deprecation" })
public class Json {

	private static Log log = LogFactory.getLog(Json.class);

	private static ObjectMapper mapper = new ObjectMapper();

	static {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		mapper.getSerializationConfig().setDateFormat(df);
		mapper.getDeserializationConfig().setDateFormat(df);
	}

	/**
	 * 将JSON字符串转成对应的对象 注意：如果转成List<MyBean>形式使用parseArray
	 * 
	 * @param <T>
	 *            clazz是什么类型转成的就是什么类型
	 * @param str
	 *            JSON字符串
	 * @param clazz
	 *            转成对应的对象 List--LinkedHashMap
	 * @return <T> T
	 */
	public static <T> T parseObject(String str, Class<T> clazz) {
		try {
			if (Ts.hv(str)) {
				return mapper.readValue(str, clazz);
			}
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		return null;
	}

	/**
	 * 将JSON字符串转换成：List<MyBean>
	 * 
	 * @param <T>
	 * @param str
	 *            JSON字符串
	 * @param clazz
	 *            转成对应的对象
	 * @return <T> T
	 */
	public static <T> T parseArray(String str, Class clazz) {
		try {
			if (Ts.hv(str)) {
				return mapper.readValue(str, TypeFactory.collectionType(ArrayList.class, clazz));
			}
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		return null;
	}

	/**
	 * 将Object转成JSON字符串
	 * 
	 * @param obj
	 *            需要转成JSON字符串的对象
	 * @return String
	 */
	public static String toJson(Object obj) {
		try {
			return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			log.info(e.getMessage());
		}
		return null;
	}

	/**
	 * 获取ObjectMapper对象
	 * 
	 * @return ObjectMapper
	 */
	public static ObjectMapper getMapper() {
		return mapper;
	}
}
